﻿using System.Drawing;
using System.IO;
using PlanningGIS.DataCheck.form;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.ADF.BaseClasses;
using PlanningGIS.Framework;

using PlanningGIS.DataCheck.model;
using PlanningGIS.Framework.Controls;
using ESRI.ArcGIS.Geodatabase;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Util.Log;

namespace PlanningGIS.DataCheck.button
{
  
    internal class btnArteryCheck : BaseCommand
    {
        IApplication m_Application = null;

        public btnArteryCheck()
        {
            base.m_caption = "交通主次干道检查";
            base.m_toolTip = base.m_caption;
        }


        public override void OnCreate(object hook)
        {
            m_Application = hook as IApplication;
        }


        public override int Bitmap
        {
            get
            {
                string bitmapResourceName = "PlanningGIS.DataCheck.Res." + this.GetType().Name + ".png";
                System.IO.Stream pStream = GetType().Assembly.GetManifestResourceStream(bitmapResourceName);
                if (pStream == null) return 0;
                return new Bitmap(pStream).GetHbitmap().ToInt32();
            }
        }

        public override bool Enabled
        {
            get
            {
                return (m_Application as IFramework).IsMapCtrlactive;
            }
        }

        public override void OnClick()
        {
            if ((m_Application as IFramework).IsMapCtrlactive)
            {
                try
                {
                    
                    IMapControl3 pMapControl = (m_Application as IFramework).MapControl;
                    FrmArteryCheck myform = new FrmArteryCheck(pMapControl.Map);
                    if (myform.ShowDialog((m_Application as IFramework).MdiForm) == DialogResult.OK)
                    {
                        bool isChecking = false;//是否处在检查状态
                        bool isInterrupt = false;//在检查的过程中是否被终止

                        AteryCheck pCheck = new AteryCheck();
                        
                        pCheck.Map = pMapControl.Map;

                        int rst = pCheck.Check("主次干道代码异常", MapHelper.GetFirstLayer<IFeatureLayer>(pMapControl.Map, myform.LyrNameLn), myform.Extent,
                            "", myform.FcodeField, myform.NameField);

                        if (rst != -1)
                        {
                            MsgHelper.ShowInfomationMsgbox("检查完毕！");
                        }
                        else
                        {
                            MsgHelper.ShowWarningMsgbox("检查失败，具体信息请查看详细日志！");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowErrorMsgbox("检查失败：" + ex.Message);
                }
            }
        }
    }


    public class AteryCheck : Check
    {
        private void CheckPoint(IGeometry pGeometry, IFeature pFeature, ISelectionSet pSelectionSet, IFeatureLayer pFeatLyr,
            string fcodeField ,string nameField)
        {
            try
            {
                IFeatureClass pFeatCls = pFeatLyr.FeatureClass;

                int idxfcode = pFeatCls.FindField(fcodeField);
                int idxname = pFeatCls.FindField(nameField);

                string fcode = pFeature.get_Value(idxfcode).ToString();
                string name = pFeature.get_Value(idxname).ToString();

                IGeometry pGeombuffer = GeometryHelper.GetBuffer(pGeometry, 10, (pFeatCls as IGeoDataset).SpatialReference);
                ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                pSpatialFilter.Geometry = pGeombuffer;
                pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                pSpatialFilter.GeometryField = pFeatCls.ShapeFieldName;
                pSpatialFilter.WhereClause = nameField + " = '" + name + "' and " + fcodeField + " <> '" + fcode + "'";

                ICursor pCursor;
                pSelectionSet.Search(pSpatialFilter, false, out pCursor);
                IFeatureCursor pFeatCur = pCursor as IFeatureCursor;
                IFeature pFeature2 = pFeatCur.NextFeature();
                while (pFeature2  != null)
                {
                    RecordListHelper.AddRecordItem("主次干道代码不一致", pFeatLyr, null, pFeature, pFeature2, pGeometry, name);
                    pFeature2 = pFeatCur.NextFeature();
                }
                DataCheckUtility.ReleaseComObject(pCursor);
                DataCheckUtility.ReleaseComObject(pFeatCur);
            }
            catch (Exception ex)
            {
               LogHelper.WriteErrLog("检查[" + pFeature.OID + "]失败：" + ex.Message);
            }
        }

        public int Check(string errType, IFeatureLayer pFeatLyrLn, IGeometry pGeometry,
            string whereClause, string fcodeField, string nameField)
        {

            List<string> fcodes = new List<string>() { "430202316", "430203316", "430204316" };
            IFeatureClass pFeatClsLn = pFeatLyrLn.FeatureClass;

            if (pFeatClsLn.ShapeType != esriGeometryType.esriGeometryPolyline)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层不是线状图层，检查失败！");
                return -1;
            }

            int idxfcodeln = pFeatClsLn.FindField(fcodeField);
            if (idxfcodeln == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到分类代码[" + fcodeField + "]字段，检查失败！");
                return -1;
            }

            int idxname = pFeatClsLn.FindField(nameField);
            if (idxname == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到名称[" + nameField + "]字段，检查失败！");
                return -1;
            }

            string sql = fcodeField + " in ('";
            foreach (string fcode in fcodes)
            {
                sql = sql + fcode + "','";
            }
            sql = sql.Substring(0, sql.Length - 2) + ") and " + nameField + " is not null";
            IQueryFilter pQueryFilter = new QueryFilterClass();
            pQueryFilter.WhereClause = sql;

            ISelectionSet pSelectionSet;
            IFeatureSelection pFeatSel = (IFeatureSelection)pFeatLyrLn;
            pSelectionSet = CursorHelper.GetSelset(pFeatSel, extent, sql, esriSpatialRelEnum.esriSpatialRelIntersects);
            setProcessBarMax(pSelectionSet.Count);

           
            int count = 0;
            int errCount = 0;


            while (pSelectionSet.Count > 0)
            {
                IEnumIDs ids;
                int id;

                if (IsStop()) break;

                setProcessBarCurrent(++count);

                List<int> lstId = new List<int>();

                ids = pSelectionSet.IDs;
                ids.Reset();
                id = ids.Next();
                lstId.Add(id);

                IFeature pFeatHold = pFeatClsLn.GetFeature(id);

                IPolyline pPolyline = (pFeatHold.ShapeCopy) as IPolyline;
                CheckPoint(pPolyline.FromPoint, pFeatHold, pSelectionSet, pFeatLyrLn, fcodeField, nameField);
                CheckPoint(pPolyline.ToPoint, pFeatHold, pSelectionSet, pFeatLyrLn, fcodeField, nameField);

                IGeoDatabaseBridge2 pGeoDatabaseBridge2 = new GeoDatabaseHelperClass();

                int[] OIDList = lstId.ToArray();

                pGeoDatabaseBridge2.RemoveList(pSelectionSet, ref OIDList);

            }

            LogHelper.WriteLog("检查结束。\n");

            return errCount;
        }

    }
}
